<?php
namespace Swork\Server\Tcp;

use Swork\Bean\Holder\ControllerHolder;
use Swork\Bean\Holder\InstanceHolder;
use Swork\Exception\TcpException;
use Swork\Middleware\MiddlewareProcessor;

/**
 * TCP接收处理器
 * Class TcpReceive
 * @package Swork\Server\Tcp
 */
class TcpReceive
{
    /**
     * 全局环境变量
     * @var array
     */
    private $env;

    /**
     * Request constructor.
     * @param array $env
     */
    public function __construct(array $env)
    {
        $this->env = $env;
    }

    /**
     * tcp回调
     * @param TcpArgument $argument
     * @return mixed
     * @throws
     */
    function handler(TcpArgument $argument)
    {
        //获取Class
        $cls = ControllerHolder::getClass($argument->getUri(), $params);
        if ($cls == false)
        {
            throw new TcpException('Can not find the router.', 9001);
        }
        if ($params != null)
        {
            $argument->setParams($params);
        }

        //实例化
        $ins = InstanceHolder::getClass($cls[0]);
        if ($ins == false)
        {
            throw new TcpException('Can not find the class.', 9002);
        }

        //处理调用前中间件
        $mp = MiddlewareProcessor::beforeMiddleware($cls, $argument);
        if ($mp === false)
        {
            $argument->setBreak();
            return null;
        }

        //调用方法
        $method = $cls[1];

        //执行调用并返回
        $result = $ins->$method($argument);

        //处理调用后中间件
        MiddlewareProcessor::afterMiddleware($cls, $argument, $result);

        //返回
        return $result;
    }
}
